package com.woniu.learnfile.controller;

import com.woniu.learnfile.entity.ErrorResult;
import com.woniu.learnfile.service.Impl.SaveFileLocalServiceImpl;
import org.apache.http.entity.ContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Map;

/**
 * created  by woniu201
 * created in 2018/3/13
 */
@RestController
public class UploadController extends BaseController{

    @Autowired
    SaveFileLocalServiceImpl saveFileLocal;

    @RequestMapping(value="/test",method= RequestMethod.POST)
    public ResponseEntity<?> uploadFile(HttpServletRequest request){

        System.out.println(ContentType.MULTIPART_FORM_DATA.getMimeType());
        System.out.println(request.getContentType());
        //只支持Content-Type为 multipart/domain-data的类型
        if (request.getContentType().equals(ContentType.MULTIPART_FORM_DATA.getMimeType())){
            return fail(400.1, "ContentType error"+ request.getContentType(), HttpStatus.BAD_REQUEST);
        }

        MultipartHttpServletRequest params = ((MultipartHttpServletRequest) request);

        String user = params.getParameter("user");
        System.out.println(user);

        //读文件
        Map<String, MultipartFile> files = params.getFileMap();
        //MultipartFile file = null;
        for (Map.Entry<String, MultipartFile> entry : files.entrySet()){
            System.out.println("file字段名：" + entry.getKey());
            MultipartFile file = entry.getValue();
            if (!file.isEmpty()){
                byte[] fileBytes = new byte[0];
                try {
                    fileBytes = file.getBytes();
                    System.out.println(entry.getValue().getOriginalFilename());
                    if(!saveFileLocal.saveFile(file.getOriginalFilename(),fileBytes)){
                        return fail(new ErrorResult(400.2, "文件保存失败"), HttpStatus.BAD_REQUEST);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                //System.out.println(new String(fileBytes));
            }

        }
        return success("ok");
    }
}
